package pl.ptemich.network.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {

  private ServerSocket serverSocket;
  
  private Socket clientSocket;
  
  private BufferedReader reader;
  
  private PrintStream writter;
  
  private String line;
  
  public void init() throws IOException {
    serverSocket = new ServerSocket(2222);
  }

  public void startListening() {
    System.out.println("The server started. To stop it press <CTRL><C>.");
    try {
      clientSocket = serverSocket.accept();
      reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
      writter = new PrintStream(clientSocket.getOutputStream());

      /* As long as we receive data, echo that data back to the client. */
      while (true) {
        line = reader.readLine();
        writter.println("From server: " + line);
        System.out.println(line);
        if ("Ok".equals(line)) {
          break;
        }
      }
      
      reader.close();
      writter.close();
    } catch (IOException e) {
      System.out.println(e);
    }    
    System.out.println("Stop server");
  }
}
